<template>
  <div v-if="tableInfo.length > 0">
      <el-table ref="table" :data="tableData" style="width: 100%" border highlight-current-row
      @selection-change="handleSelectionChange"   :summary-method="getSummaries"
      :show-summary="handlerKeyName()"
      @row-click="handleRowClick" class="draggable-table">
        <!-- <el-table-column v-if="tableInfo.length > 0" width="50" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
             <div>{{ scope.$index + 1 }}</div>
          </template>
          :width="
            [
              'input_percentage',
              'tag',
              'textarea',
              'date_picker',
              'date_time_picker',
              'cascader',
              'cascader_address'
            ].includes(item.form_value)
              ? 150
              : ''
          "
        </el-table-column> -->
        <el-table-column label="" width="50" align="center">
            <template #default>
                <i class="el-icon-rank drag-handle"></i>
            </template>
         </el-table-column>
         <el-table-column type="selection" align="center" width="50" show-overflow-tooltip> </el-table-column>
         <el-table-column
          v-for="(item, index) in tabelHeader"
          :prop="item.field_name_en"
          :label="item.field_name"
          :key="index"
          align="center"
          :min-width="handlerWidth(item)">
          <template slot-scope="scope">
              <div style="text-align:center;">
                <div v-if="item.field_name_en=='wuliaobianmaid'" >{{ scope.row[item.field_name_en] }}</div>
                <div v-else-if="item.field_name_en=='item_depc'">
                   <p style="font-size:13px;line-height:18px;" class="tabelnumellpis">{{ scope.row[item.field_name_en] }}</p>
                </div>
                <div v-else-if="item.form_value === 'textarea'" >
                  <div>
                    <div v-if="keyName=='gongxushezhong'">
                        <div v-if="item.field_name_en=='beizhu'">
                          <el-input type="textarea" v-model="scope.row[item.field_name_en]" :rows="1" style="border:none;" ></el-input>
                        </div>
                        <div v-else class="tabelnumellpis">
                          {{ scope.row[item.field_name_en] }}
                        </div>
                    </div>
                    <div v-else>
                      <el-input type="textarea" v-model="scope.row[item.field_name_en]" :rows="1" style="border:none;" :disabled="scope.row[item.disabled]" ></el-input>
                    </div>
                  </div>
                </div>
                <div v-else-if="item.field_name_en === 'bumenid'">
                  <el-select v-model="scope.row[item.field_name_en]" placeholder="请选择或搜索" filterable  :disabled="scope.row[item.disabled]" >
                      <el-option
                        v-for="item in zidianData[item.field_name_en]"
                        :key="item.id"
                        :label="item.zhongwenmiaoshu + ' ('+item.gongxudaima+') ' "
                        :value="item.gongxudaima">
                      </el-option>
                    </el-select>
                </div>
                <div v-else-if="item.form_value ==='radio'">
                    <el-select v-model="scope.row[item.field_name_en]" placeholder="请选择" :disabled="scope.row[item.disabled]">
                      <el-option
                        v-for="itema in zidianData[item.field_name_en]"
                        :key="itema.id"
                        :label="itema.name"
                        :value="itema.value+''">
                      </el-option>
                    </el-select>
                </div> 
                <div v-else-if="item.form_value ==='input_select'">
                    <!-- {{ item.field_name_en }}/{{ scope.row[item.field_name_en] }} -->
                    <div v-if="item.field_name_en=='bengongxuid'">
                      <el-select v-model="scope.row[item.field_name_en]" placeholder="请选择" :disabled="scope.row[item.disabled]"  
                      @change="getbenggongchange($event, zidianData[item.field_name_en], scope.$index)" >
                        <el-option
                          v-for="itema in zidianData[item.field_name_en]"
                          :key="itema.id"
                          :label="itema.zhongwenmiaoshu"
                          :value="itema.id">
                        </el-option>
                      </el-select>
                    </div>
                    <div v-else-if="item.field_name_en=='daogongxuid'">
                      <el-select v-model="scope.row[item.field_name_en]" placeholder="请选择" :disabled="scope.row[item.disabled]" >
                        <el-option
                          v-for="itema in zidianData[item.field_name_en]"
                          :key="itema.id"
                          :label="itema.zhongwenmiaoshu"
                          :value="itema.id">
                        </el-option>
                      </el-select>
                    </div>
                    <div v-else-if="item.field_name_en=='shiyongbumen'">
                      <el-select v-model="scope.row[item.field_name_en]" placeholder="请选择" :disabled="scope.row[item.disabled]" >
                        <el-option
                          v-for="itema in zidianData[item.field_name_en]"
                          :key="itema.id"
                          :label="itema.zhongwenmiaoshu"
                          :value="itema.id">
                        </el-option>
                      </el-select>
                    </div>
                    <div v-else>
                      <span v-if="keyName=='gongxushezhong'">{{ scope.row[item.field_name_en] }}</span>
                      <span v-else>
                      <el-select v-model="scope.row[item.field_name_en]" placeholder="请选择" :disabled="scope.row[item.disabled]" >
                        <el-option
                          v-for="itema in zidianData[item.field_name_en]"
                          :key="itema.id"
                          :label="itema.zhongwenmiaoshu"
                          :value="itema.id+''">
                        </el-option>
                      </el-select>
                      </span>
                    </div>
                    
                </div> 
                <div v-else-if="item.form_value=='cascader_radio'">
                    <div v-if="handlerdisabel(item.field_name_en)">{{ hadnlerArray(scope.row[item.field_name_en], zidianData[item.field_name_en]) }}</div>
                    <div v-else>
                        <el-select v-model="scope.row[item.field_name_en]" placeholder="请选择" :disabled="scope.row[item.disabled]">
                          <el-option
                            v-for="itema in zidianData[item.field_name_en]"
                            :key="itema.id"
                            :label="itema.name"
                            :value="itema.value+''">
                          </el-option>
                        </el-select>
                    </div>
                </div>
                <div v-else-if="item.form_value=='date_picker'">
                  <div v-if="handlerdisabel(item.field_name_en)">
                      {{ scope.row[item.field_name_en] }}
                  </div>
                  <div v-else>
                    <el-date-picker style="width:90px;" 
                      v-model="scope.row[item.field_name_en]" format="yyyy-MM-dd"
                      type="date" value-format="yyyy-MM-dd"
                      placeholder="选择日期" :picker-options="pickerOptions">
                    </el-date-picker>
                  </div>
                </div>
                <div v-else-if="item.form_value=='date_time_picker'">
                  <div v-if="handlerdisabel(item.field_name_en)">
                      {{ scope.row[item.field_name_en] }}
                  </div>
                  <div v-else>
                    <el-date-picker style="width:90px;" 
                        v-model="scope.row[item.field_name_en]" format="yyyy-MM-dd"
                        type="date" value-format="yyyy-MM-dd"
                        placeholder="选择日期" :picker-options="pickerOptions">   
                    </el-date-picker>
                  </div>
                  
                </div>
                <div v-else-if="item.field_name_en=='shiyongbumen'">
                    <el-select v-model="scope.row[item.field_name_en]" placeholder="请选择" :disabled="scope.row[item.disabled]" >
                      <el-option
                        v-for="item in zidianData[item.field_name_en]"
                        :key="item.id"
                        :label="item.zhongwenmiaoshu"
                        :value="item.gongxudaima">
                      </el-option>
                    </el-select>
                </div>
                <div v-else-if="item.form_value=='switch'">
                  {{ item.field_name_en }}
                  <el-switch :width="swidth"
                    v-model="scope.row[item.field_name_en]"
                    active-color="#13ce66"
                    inactive-color="#c0c0c0"
                    :active-value="1"
                    :inactive-value="0">
                  </el-switch>
                </div>
                <div v-else>
                    <!-- {{ item.form_value }} -->
                    <div v-if="item.field_name_en=='unitName'">{{ scope.row[item.field_name_en] }}</div>
                    <div v-else-if="item.field_name_en=='guigedaima' || item.field_name_en=='guigeleixing' || item.field_name_en=='zhongwenmingcheng' || item.field_name_en=='gongyingshangdaima' || item.field_name_en=='kehao' || item.field_name_en=='kezhongwenmingcheng' ">
                      {{ scope.row[item.field_name_en] }}
                    </div>
                    <div v-else>
                        <div v-if="getVal(scope.row[item.field_name_en])==1" class="tabelnumellpis">
                           <!-- {{ item.field_name_en }}C / {{ getVal(scope.row[item.field_name_en], item.field_name_en) }}/B -->
                          {{  scope.row[item.field_name_en].name}}
                        </div>
                        <div v-else-if="getVal(scope.row[item.field_name_en], item.field_name_en)==2">
                            <!-- {{ item.field_name_en }}B -->
                            <div v-if="scope.row[item.field_name_en] && scope.row[item.field_name_en].length > 0" class="tabelnumellpis">
                                {{ scope.row[item.field_name_en] }}
                               <!-- {{  scope.row[item.field_name_en].join(",") }} -->
                            </div>
                        </div>
                        <div v-else>
                          <div v-if="item.field_name_en=='sunhao'" >
                             <div style="min-width:60px;min-height:28px;" @click="goSunhaoClick(scope.row,scope.$index)">
                                <div v-if="scope.row[item.field_name_en] && scope.row.sunhaoleixing==1">
                                  <div v-for="(itemc, indexc) in handerJSONdata(scope.row[item.field_name_en])" :key="indexc">
                                     <div v-if="itemc.value2">{{ itemc.value2 }}:{{ itemc.value3 }},</div>
                                  </div>
                                </div>
                             </div>
                          </div>
                          <div v-else>
                             <div v-if="handlerdisabel(item.field_name_en)" class="tabelnumellpis">
                              {{ scope.row[item.field_name_en] }}
                             </div>
                             <div v-else>
                                <el-input type="input" v-model="scope.row[item.field_name_en]" @change="handlerMoneyjs($event,item.field_name_en, scope.row)"></el-input>
                             </div>
                          </div>
                        </div>
                    </div>
                </div>
              </div> 
          </template>
        </el-table-column>
      </el-table>
      <div>
         <sunhaoIndex ref="editsunhao" v-if="AddDrawernewsunhao" :status="1"  @handlersunhaoSubmit="handlersunhaoSubmit"></sunhaoIndex>
      </div>
  </div>
</template>
<script>
import Sortable from 'sortablejs'
import { getDictDatainfoApi, getDictDataListApi } from '@/api/form'
import { databaseInfoApi, crudModuleListApi } from '@/api/develop'
import { EventBus } from '@/libs/bus'
import sunhaoIndex from '@/components/sunhaoForm/index.vue'
import AddDrawernew from '@/views/develop/module/components/addDrawernew.vue'
export default {
  name: 'HelloWorld',
  components: { sunhaoIndex },
  data() {
      return {
          msg: 'table',
          tabelHeader:[],
          tabelBody: [],
          swidth:20,
          // zidianData:{},
          dictForm: {
                types: '',
                level: 1,
                pid:''
          },
          drawer: false,
          sunhaoId: 0,
          AddDrawernewsunhao: false,
          selectrowIndex: 0,
          isflage: false,
          pickerOptions: {
           
            onPick(value) { // 当选择日期时触发，可以用来更新视图或进行其他操作
              // 例如，更新视图显示选择的日期或其他信息
            }
          }
      }
  },
  props: {
      tableData: {
        type: Array,
        default: () => {
              return []
        }
      },
      tableInfo: {
          type: Array,
          default: ()=> {
              return []
          }
      },
      zidianData: {
          type: Object,
          default: ()=> {
              return {}
          }
      },
      selectDialogIndex: {
          type: [Number, String],
          default: 0
      },
      keyName: {
          type: String,
          default: '',
      },
      tableName: {
        type: String,
        default: '',
      },
      disabledfiled: {
         type: [Array, Object],
         default: ()=>{
            return []
         }
      }
  },
  watch: {
      tableInfo(newval, oldnew){
         if(newval !== oldnew){
             this.tabelHeader = this.tableInfo
             for(let i=0;i<this.tabelHeader.length;i++){
                if(this.tabelHeader[i].field_name_en =='wuliaodanganid' || this.tabelHeader[i].field_name_en =='wuliaoleibiebianmaid' ){
                   this.tabelHeader.splice(i, 1)
                }
             } 
             let dictTime = setTimeout(()=>{
                this.initSortable();
                clearTimeout(dictTime)
             }, 1000)
         }
      },
  },
  mounted(){   

  },
  beforeDestroy() {
      EventBus.$off('handlergrandIndex', '')
  },
  methods: {
      // 根据数量和单价计算金额
      handlerMoneyjs(event,field, row){
        if(this.tableName=='xiaoshoumingxi'){ // 销售明细
           if(field == 'shuliang'){ // 数量
             if(event){
               let sumMoney = parseFloat(event) * (parseFloat(row.danjia || 0) * 10000)
               row.jine = sumMoney / 10000;
             }else{
                row.jine = 0;
             }
           }else if(field == 'danjia'){
              if(event){
               let sumMoney = (parseFloat(event) * 10000) * parseFloat(row.shuliang || 0)
               row.jine = sumMoney / 10000;
              }else{
                row.jine = 0;
              }
           }
        }

      },
      handlerKeyName(){
          if(this.tableName == 'xiaoshoumingxi'){ // 销售明细
              return true;
          }else{ 
              return false;
          }

      },
      getSummaries(param) {
          const { columns, data } = param;
          const sums = [];
          columns.forEach((column, index) => {
            if (index === 0) {
              sums[index] = '';
              return;
            }
            const values = data.map(item => Number(item[column.property]));
            if(column.property=='shuliang' || column.property=='mianfeishu' || column.property=='jine'){
              if (!values.every(value => isNaN(value))) {
                sums[index] = values.reduce((prev, curr) => {
                  const value = Number(curr);
                  if (!isNaN(value)) {
                    return prev + curr;
                  } else {
                    return prev;
                  }
                }, 0);
                sums[index] += '';
              } else {
                sums[index] = '';
              }
            }else{
              sums[index] = ''
            }
          });
          return sums;
        
      },
      // 本工序选择事件
      getbenggongchange(val, list, index){
        if(val){
           let laiyuan = null
           for(let i=0;i< list.length;i++){
             if(val == list[i].gongxudaima){
                laiyuan = list[i].laiyuan;
                break;
             }
           }
           if(laiyuan && laiyuan.length > 0){
              let laiyuanname  = laiyuan.join(",")
              let laiyuanVal = null;
              let laiyuandata = this.zidianData.laiyuan
              for(let i=0;i<laiyuandata.length;i++){
                 if(laiyuanname == laiyuandata[i].name){
                    laiyuanVal = laiyuandata[i].value;
                    break;
                 }
              }
              this.$emit("changeBack",1, index, laiyuanVal)
           }
        }

      },
      handlerWidth(item){
         let itemdata =  [
              'input_percentage',
              'tag',
              'date_picker',
              'date_time_picker',
              'cascader',
              'cascader_radio',
              'cascader_address',
              'input_select'
          ]
          let itemtext = ['zhongwenmiaoshu','wuliaozhongwenmiaoshu', 'item_depc', 'item_sn', 'beizhu', 'remark','fangdanmiaoshu']
          let itemtext2 = ['wuliaobianma', 'bumenid'];
          let itemtext3 = ['kechima', 'kekuanhao']
          let itemfiled = ['switch']
          let itemtext4 = ['danwei', 'unit', 'zhuangtai', 'jishu', 'laiyuan','source']
          if(itemtext.includes(item.field_name_en)){
             return '200px'
          }
          if(itemtext2.includes(item.field_name_en)){
             return '140px'
          }
          if(itemtext3.includes(item.field_name_en)){
             return '100px'
          }
          if(itemtext4.includes(item.field_name_en)){
             return '60px'
          }
          if(itemfiled.includes(item.form_value)){
             return '60px'
          }
          if(itemdata.includes(item.form_value)){
             return '90px'
          }
          return '70px'
      },
      // 限制显示字数
      handlerClass(val){
         if(val.length > 20){
             return 'tabelnumellpis'
         }else{
            return ''
         }
      },
      // 初始化拖拽排序
      initSortable() {
            const table = this.$refs.table
            const tbody = table.$el.querySelector('.el-table__body-wrapper tbody')
            this.sortable = new Sortable(tbody, {
                animation: 150,
                handle: '.drag-handle',
                ghostClass: 'ghost',
                onEnd: ({ newIndex, oldIndex }) => {
                const currRow = this.tableData.splice(oldIndex, 1)[0]
                // this.tableData.splice(newIndex, 0, currRow)
                // this.$set(this.tableData, this.tableData)
                this.$emit('selectTabel', {new: newIndex, old: oldIndex, row: currRow}, 1);
                }
            })
      },
      goSunhaoClick(row, index){
        this.selectrowIndex = index;
        this.status = 1;
        this.AddDrawernewsunhao = true;
        this.$nextTick(() => {
          this.$refs.editsunhao.openBox(0, row)
        })
      },
      // 损耗提交返回
      handlersunhaoSubmit(val, index=0){
          this.drawer = false;
          this.$emit("changeBack",2, this.selectrowIndex, val)
      },
      // 弹窗关闭
      handleClose(){
          this.drawer = false;
      },
      async handlerDict(){
          let itemdata = this.tabelHeader;
          let obj = {}
          for(let i=0;i<itemdata.length;i++){
             if(itemdata[i].data_dict_id){ // 字典查询下拉选择框数据
               obj[itemdata[i].field_name_en] = []
                let dataictnamearr = []
                let datadict = await getDictDatainfoApi(itemdata[i].data_dict_id)
                dataictnamearr.push(datadict.data.ident);
                this.dictForm.types = dataictnamearr;
                let datadictDta = await getDictDataListApi(this.dictForm)
                obj[itemdata[i].field_name_en] = datadictDta.data.list;
             }else if(itemdata[i].association_crud_id){ // 关联表选择查询
                let database = await databaseInfoApi(itemdata[i].association_crud_id)
                let tabbasename = database.data.table_name_en;
                let datalist = await crudModuleListApi(tabbasename, {page: 1, limit: 100});
                obj[itemdata[i].field_name_en] = datalist.data.list;
             }
          }
          this.zidianData = obj;
      },
      // 选择行事件
      handleRowClick(row){

      },
      /**
       * 处理选择项变化
       *
       * @param val 选择项数组
       */
      handleSelectionChange(val) {
          let selectid = []
          if(val.length > 0){
             val.map((item, index)=>{
                if(this.keyName=='gongyi'){
                  if(item.id){
                     selectid.push(item.id)
                  }else{
                     selectid.push(item.deleteid)
                  }
                }else{
                  selectid.push(item[this.tableInfo[0].field_name_en])
                }
             })
          }
          console.log("selectid", selectid)
          this.$emit('selectTabel', selectid);
      },
      getVal(val,field){
        if(val){
          if(this.goisObjectOrArray(val)){
              return 1;
          }else if(this.goisArray(val)){
              if(val.length > 0){
                  return 2;
              }else{
                return ''
              }
          }else {
            return 3;
          }
        }else{
          return ''
        }
      },
      goisObjectOrArray(val) {
        return Object.prototype.toString.call(val) === '[object Object]' || Array.isArray(val);
      },
      goisArray(val) {
        return Array.isArray(val);
      },
      handerJSONdata(data){
         if(this.goisArray(data)){
             return data;
         }else if(data){
            return JSON.parse(data)
         }else{
            return ''
         }
      },
      handlerModel(val){
        if(val){
           let newStr =''
           if(val.includes("/")){
              newStr = val.replace(/\//g, "");
           }else{
              newStr = val;
           }
           return newStr
        }else{
           return ''
        }
      },
      handlerxiegang(val, data){
        if(val){
          if(val.includes("/")){
            let newStr = val.replace(/\//g, "");
            if(data && data.length > 0){
              for(let i=0;i < data.length; i++){
                  if(data[i].value == newStr){
                      return data[i].name;
                  }
              }
            }
          }else{
            let newStr = val
            if(data && data.length > 0){
              for(let i=0;i < data.length; i++){
                  if(data[i].value == newStr){
                      return data[i].name;
                  }
              }
            }
          }
        }
        return ''
      },
      // 判断数据是否可修改
      handlerdisabel(val){
          if(this.disabledfiled.length > 0){
             if(this.disabledfiled.includes(val)){
                return true;
             }
          }else{
             return false;
          }
      },
      // 对数据进行格式化处理
      hadnlerArray(val, data){
         if(this.goisArray(val)){
            if(val && val.length > 0){
               return val.join(",");
            }else{
               return ''
            }
         }else{
            if(val){
              if(data && data.length > 0){
               for(let i=0;i<data.length;i++){
                 if(val == data[i].value || val == data[i].name){
                     return data[i].name;
                 }
               }
              }else{
                return val;
              }
            }else{
               return ''
            }
         }
      }

  },
}

</script>
<style scoped>
/deep/ .el-table tr{
   height:36px;
}
/deep/ .el-input__icon{
   width:20px;
}
/deep/ .el-switch__core{
   min-width:40px;
}
/deep/ .draggable-table .el-textarea__inner{
  border:none!important;
}
/deep/ .draggable-table .el-input__inner{
  border:none!important;
}
/deep/ .el-checkbox__inner{
    width:16px;height:16px;
}
/deep/ .el-input--suffix .el-input__inner{
   padding: 0 4px!important;
}
/deep/ .el-input__inner{
   padding: 0 5px!important;
}
/deep/ .el-table .cell{
  padding:0 2px!important;
}
/deep/ .el-table--medium .el-table__cell{
   padding:2px 0!important;
}
/deep/ .el-icon-date:before{
  content: '';
}
/deep/ .el-table .cell{
  line-height: 18px;
}
/deep/ .draggable-table .el-input--medium .el-input__inner{
  height:28px;line-height:28px;font-size:12px;
}
/deep/ .el-table td.el-table__cell div p{
   margin-bottom: 0.2rem;font-size:12px!important;line-height:16px!important;
}
/deep/ .el-date-editor.el-input{
   width:110px!important;
}
/* select 上拉箭头 */
/deep/ .el-icon-arrow-up:before{
   content:''
}
/deep/ .draggable-table .el-input--medium .el-input__icon.el-icon-circle-close{
   line-height:28px!important;
}
/deep/ .wrapper tbody td.el-table__cell{
   font-weight: 600;
}
.tabelnumellpis{
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  line-height: 18px;
  padding:3px 0;
  font-size:13px;
}
</style>